package com.eportal.service.impl;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.eportal.action.background.pojo.Page;
import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.domain.LifeResource;
import com.eportal.domain.LifeStrategy;
import com.eportal.domain.Sysopt;
import com.eportal.domain.TCommunity;
import com.eportal.exception.JdbcException;
import com.eportal.service.LifeResourceService;
import com.eportal.service.TCommunityService;
import com.eportal.util.Config;
import com.eportal.util.ImageCut;
import com.eportal.util.UploadUtil;

import net.sf.json.JSONObject;


@Service("lifeResourceService")
public class LifeResourceServiceImpl  implements LifeResourceService {
	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(LifeResourceServiceImpl.class.getName());
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }
	@Resource(name="dao")
	private BaseDAO dao;
	@Autowired
    private TCommunityService tCommunityService;
    @Override
    public LifeResource add(LifeResource lifeResource) throws Exception {
    	dao.save(lifeResource);
        return lifeResource;
    }

    @Override
    public void update(LifeResource lifeResource) throws JdbcException {
    	 dao.update(lifeResource);
    }

    @Override
    public void delete(long id) {
            LifeResource lifeResource = (LifeResource) dao.getById(LifeResource.class, id);
           dao.delete(lifeResource);
    }


    @Override
    public Page find(String where, Page page) {
        final StringBuffer hql = new StringBuffer("select t.*,a.agtName  from life_resource t left join t02_agtent a on t.agtcode=a.agtcode where 1=1 ");
        hql.append(where);
        String countsql = "select count(*) from (" + hql.toString() + ") bb";
        int count = dao.count(countsql);
        List<Map<String, Object>> list = dao.queryBySql("select * from (select bb.*,rownum rownum_bb from (" + hql.toString() + " order by t.sid DESC ) bb where rownum<= " + (page.getCurrentPage() * page.getPageSize()) + ")" + " where rownum_bb>" + (page.getCurrentPage() - 1) * page.getPageSize());
        return new Page(page.getCurrentPage(), page.getPageSize(), count, list);
    }

    @Override
    public LifeResource get(long id) {
        return (LifeResource) dao.getById(LifeResource.class, id);
    }
    
    
	@Override
	@LogAnnotation(operateDescribe="生活服务管理资源上架")  
	public Map<String, Object> addMethod(LifeResource lifeResource) {
		try {
			
			lifeResource.setIsOnLine(1);
			Sysopt user =(Sysopt)getSession().getAttribute("user");
			lifeResource.setcUser(Long.toString(user.getSid()));
			lifeResource.setcTime(new Date());
			int userRole =  (Integer) getSession().getAttribute("userRole");
			if (userRole == 1 || userRole == 2 || userRole == 21) {
				lifeResource.setdType("1");
			}else if (userRole == 3 || userRole == 4) {
				lifeResource.setAgtCode(user.getAgtCode());
				lifeResource.setdType("2");
	    	}else{
	    		result.put("code", 0);
	  	        result.put("msg", "权限不足，操作失败");
	    	}
			add(lifeResource);
			result.put("code", 1);
            result.put("msg", "操作成功");
		} catch (Exception e) {
			 log.error("生活服务管理资源新增失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}
	
	@Override
	public Map<String, Object> picCutUpload(File file, String fileName, String putData, String path) {
		 try {
			 JSONObject obj =  JSONObject.fromObject(putData);
			 float x = Float.parseFloat(obj.getString("x"));//坐标
			 float y = Float.parseFloat(obj.getString("y"));
			 float w = Float.parseFloat(obj.getString("width"));//宽高
			 float h = Float.parseFloat(obj.getString("height"));
			 String thePath = Config.getpath(path);
			 String destDir = ServletActionContext.getRequest().getServletContext().getRealPath(thePath);
			 if (!new File(destDir).exists()) {
				 new File(destDir).mkdirs();
			 }
			 String ext = UploadUtil.getExt(fileName);
			 String destFileName = System.currentTimeMillis() + ext;
			 String dirImageFile = destDir+File.separator+destFileName;
			 ImageCut.abscut(file, dirImageFile, (int)x, (int)y, (int)w, (int)h);
			 result.put("code", 1);
	         result.put("msg", "截图上传成功");
	         result.put("content", thePath+destFileName);
		} catch (Exception e) {
			 result.put("code", 0);
             result.put("msg", "截图上传失败");
             log.error(this, e);
		}
		 return result;
	}
	
	@Override
	public Map<String, String> getBySql(Long sid) {
		List<Map<String, String>> list= null;
		StringBuilder sql = new StringBuilder("select b.*,s.uname from life_resource b left join sysopt s on b.cuser=s.sid where b.sid=");
		sql.append(sid);
		list= dao.queryBySql(sql.toString());
		if (list.size()>0) {
			return list.get(0);
		}
		return null;
	}

	@Override
	@LogAnnotation(operateDescribe="生活服务管理资源修改")  
	public Map<String, Object> updateMethod(LifeResource lifeResource) {
		try {
			LifeResource entry = get(lifeResource.getSid());
			if (StringUtils.isNotBlank(lifeResource.getContent())) {
				entry.setContent(lifeResource.getContent());
			}
			if (StringUtils.isNotBlank(lifeResource.getcName())) {
				entry.setcName(lifeResource.getcName());
			}
			entry.setcUrl(lifeResource.getcUrl());
			entry.setExpectedIncome(lifeResource.getExpectedIncome());
			entry.setAdDetails(lifeResource.getAdDetails());
			entry.setSettlementMethod(lifeResource.getSettlementMethod());
			if (!entry.getIfShare().equals(lifeResource.getIfShare())) {
				if("0".equals(lifeResource.getIfShare())){
					changeLifeStrategy(lifeResource.getSid(),entry.getAgtCode());
				}
			}
			entry.setIfShare(lifeResource.getIfShare());
			entry.setSort(lifeResource.getSort());
			Sysopt user =(Sysopt)getSession().getAttribute("user");
			entry.setuUser(Long.toString(user.getSid()));
			entry.setuTime(new Date());
			update(entry);
			result.put("code", 1);
            result.put("msg", "操作成功");
		} catch (Exception e) {
			 log.error("生活服务管理资源新增失败", e);
             result.put("code", 0);
             result.put("msg", "操作失败");
		}
		return result;
	}

	private void changeLifeStrategy(Long shid, String agtCode) {
		LifeStrategy lifeStrategy = getLifeStrategy(shid);
		if (lifeStrategy == null || StringUtils.isBlank(lifeStrategy.getAgtCode())|| StringUtils.isBlank(lifeStrategy.getCommunityId())) {
			return;
		}
		if(lifeStrategy.getAgtCode().indexOf(","+agtCode+",")>-1){
			lifeStrategy.setAgtCode(","+agtCode+",");
		}else{
			lifeStrategy.setAgtCode("");
			lifeStrategy.setCommunityId("");
			updateLifeStrategy(lifeStrategy);
			return;
		}
		List<TCommunity> listComu = tCommunityService.listByAgtCodes(agtCode);
		String comuIds =  lifeStrategy.getCommunityId();
		StringBuffer comuids = new StringBuffer();
		for (TCommunity tCommunity : listComu) {
			String conuid = ","+tCommunity.getSid()+",";
			if (comuIds.indexOf(conuid)>-1) {
				comuids.append(tCommunity.getSid());
				comuids.append(",");
			}
		}
		if (comuids.length()==0) {
			lifeStrategy.setAgtCode("");
			lifeStrategy.setCommunityId("");
			updateLifeStrategy(lifeStrategy);
			return;
		}
		String cmu = comuids.toString();
		lifeStrategy.setCommunityId(","+cmu);
		updateLifeStrategy(lifeStrategy);
	}

	private void updateLifeStrategy(LifeStrategy lifeStrategy) {
		dao.update(lifeStrategy);
	}

	private LifeStrategy getLifeStrategy(Long shid) {
		StringBuffer sb = new StringBuffer("from LifeStrategy where shid=");
		sb.append(shid);
		return (LifeStrategy) dao.loadObject(sb.toString());
	}

	
	
}
